package org.jeecg.modules.third.openapi;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.amap.service.AmapService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 中交慧运轨迹服务
 * 中交慧联全力打造商用车车联网科技服务能力。围绕“车联网+物流”、“车
 * 联网+大数据”，为政府、物流企业、车队、车厂、货主企业提供北斗位置服务、
 * 项目解决方案、车辆安全管理等产品与服务。依托“人、车、货、企”海量物流
 * 大数据，共创物流生态数智化升级；结合自身在北斗时空应用、物流 AI、物联
 * 网等领域的专精优势打造物流数字化大数据 API 开放平台，为物流行业的降本增
 * 效，低碳运行赋能。
 */
@Service
@Slf4j
public class ZJHYOpenApiService {

    @Value(value="${zjhyopenapi.api_domain:https://openapi.zjgcpt.cn/vas}")
    private String ZJHY_API_DOMAIN;

    @Autowired
    private RedisUtil redisUtil;

    private final String ZJHY_API_TOKEN_KEY = "ZJHY_Api_Token";

    private final Integer ZJHY_API_TOKEN_KEY_EXPIRE = 86400 * 6;

    @Autowired
    private AmapService amapService;
    /**
     * 获取Token
     * @return
     */
    private String getLoginToken() {

        HyConfig systemConfig = HyConfigUtils.getConfig();
        if (systemConfig == null || !systemConfig.getXzApiIzUse()){
            throw new JeecgBootException("中交慧联轨迹查询服务未开启,请联系管理员");
        }

        String appId = systemConfig.getXzApiLoginAccount();
        String secret = systemConfig.getXzApiLoginPwd();
        if (StrUtil.isEmpty(secret) || StrUtil.isEmpty(appId)) {
            throw new JeecgBootException("中交慧联轨迹参数配置错误");
        }

        Object tokenObject = redisUtil.get(ZJHY_API_TOKEN_KEY);
        if (ObjectUtil.isNotEmpty(tokenObject)) {
            return tokenObject.toString();
        }

        Map<String, String> params = new HashMap<>();
        params.put("appId", appId);
        //params.put("secret", secret);
        params.put("secretKey",secret);
        String url = ZJHY_API_DOMAIN + "/api/v1/login";
        log.info("中交慧联请求Token参数 -> {} {}", url, JSONUtil.toJsonStr(params));
        String res = HttpUtil.post(url, JSONUtil.toJsonStr(params));
        JSONObject jsonObject = JSONObject.parseObject(res);
        log.info("中交慧联请求Token回执 <- {}", res);
        int code = jsonObject.getIntValue("code");
        if (0 != code) {
            throw new JeecgBootException("中交慧联交互失败:" + jsonObject.getString("msg"));
        }

        String token = jsonObject.getString("data");
        if (StrUtil.isEmpty(token)) {
            throw new JeecgBootException("中交慧联获取令牌异常");
        }

        redisUtil.set(ZJHY_API_TOKEN_KEY, token, ZJHY_API_TOKEN_KEY_EXPIRE);
        return token;
    }


    /**
     * 历史轨迹服务
     */
    public String queryTruckHisTrack(String vclN, String vco, String qryBtm, String qryEtm, String parkMins) {

        try {
            String token = this.getLoginToken();

            Map<String, String> params = new HashMap<>();
            params.put("vclN", vclN);
            params.put("vco", vco);
            params.put("qryBtm", qryBtm);
            params.put("qryEtm", qryEtm);
            params.put("parkMins", StringUtils.isBlank(parkMins) || parkMins.equals("0")  ? "10" : parkMins);

            String url = ZJHY_API_DOMAIN + "/api/v1/queryTruckHisTrack";

            log.info("获取中交慧联轨迹请求参数 -> {} {}", url, JSONUtil.toJsonStr(params));
            String res = HttpRequest.post(url)
                    .header("Token", token)
                    .body(JSONUtil.toJsonStr(params))
                    .execute()
                    .body()
                    ;
            //log.info("获取中交慧联轨迹回执 <- {}", res);

            JSONObject jsonObject = JSONObject.parseObject(res);
            int code = jsonObject.getIntValue("code") ;

            if (0 == code) {
                return res;
            } else if (405 == code) {
                redisUtil.del(ZJHY_API_TOKEN_KEY);
                throw new JeecgBootException("中交慧联服务令牌已过期，请重新请求数据");
            } else {
                throw new JeecgBootException("中交慧联轨迹获取失败: " + jsonObject.getString("msg"));
            }
        } catch (Exception e) {
            log.info("中交慧联车辆轨迹数据获取异常 {}" ,e.getMessage());
            e.printStackTrace();
            throw new JeecgBootException(e.getMessage());
        }
    }


    /**
     * 车辆入网验证(车牌号_颜色，例如：京 xxx_2)
     * @param vclN
     * @return
     */
    public String checkVehicleStatus(String vclN) {

        try {
            Map<String, String> params = new HashMap<>();
            String token = this.getLoginToken();
            params.put("vclN", vclN);
            String url = ZJHY_API_DOMAIN + "/api/v1/checkVehicleStatus";

            log.info("获取中交慧联入网V2请求参数 -> {} {}", url, JSONUtil.toJsonStr(params));
            String res = HttpRequest.post(url)
                    .header("Token", token)
                    .body(JSONUtil.toJsonStr(params))
                    .execute()
                    .body()
                    ;
            log.info("获取中交慧联入网V2回执 <- {}", res);

            JSONObject jsonObject = JSONObject.parseObject(res);
            int code = jsonObject.getIntValue("code") ;

            if (0 == code) {
                return res;
            } else if (405 == code) {
                redisUtil.del(ZJHY_API_TOKEN_KEY);
                throw new JeecgBootException("中交慧联服务令牌已过期，请重新请求数据");
            } else {
                throw new JeecgBootException("中交慧联入网验证失败: " + jsonObject.getString("msg"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("中交慧联入网验证异常 ,{}" ,e.getMessage());
            throw new JeecgBootException(e.getMessage());
        }
    }

}
